package com.concurrence;

import java.util.concurrent.locks.Lock;

/**
 * TwinsLockTest..
 *
 * @author Lizhong
 * @date 2019/4/4
 */
public class TwinsLockTest {
    public static void main(String[] args) throws InterruptedException {
        Lock twinsLock = new TwinsLock();
        for (int i = 0; i < 10; i++) {
            Worker worker = new Worker(twinsLock);
            worker.setDaemon(true);
            worker.start();
        }
        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000);
            System.out.println("===");
        }
        /**Out:
         *  交替打印，只有两个线程能够获取锁
         */
        Thread.sleep(100000);
    }

    static class Worker extends Thread {
        final Lock lock;

        Worker(Lock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                Thread thread = Thread.currentThread();
                try {
                    Thread.sleep(1000);
                    System.out.println(thread.getName());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
